<?php
namespace app\index\model;

use think\Model;

class Article extends Model
{
    //方法定义关联
    public function category(){
        return $this->belongsTo('Category');
    }
    public function label()
    {
        return $this->belongsToMany('Label', 'ArticleLabel');
    }
    // 获取器-cover字段
    public function getCoverAttr($value){
        // 补充完整封面的url
        $webUrl = '//'.$_SERVER['HTTP_HOST'];
        return $webUrl.config('upload_path').'/'.$value;
    }
    // 获取器-description字段
    public function getDescriptionAttr($value){
        // 补充完整文章内容里面的url
        $webUrl = '//'.$_SERVER['HTTP_HOST'];
        return str_replace(config('editor_path'), $webUrl.config('editor_path'), $value);
    }

    /**
     * 获取列表
     * @param array $where
     * @param array $whereAssoc
     * @return array|\PDOStatement|string|\think\Collection
     */
    public function getDetail($where=[], $whereAssoc=[], $currentPage=1, $pageSize=10){
        //若不指定status
        if (!in_array('status', array_column($where, 0))){
            $where[] = ['status', '>=', 0];//默认获取有效的记录
        }
        //若关联条件存在
        foreach ($whereAssoc as $key => $value){
            self::hasWhere($key, $value);
        }
        return self::where($where)->page($currentPage, $pageSize)->select();
    }

    /**
     * 获取记录总数
     * @param array $where
     * @param array $whereAssoc
     * @return float|string
     */
    public function getCount($where=[], $whereAssoc=[]){
        //若不指定status
        if (!in_array('status', array_column($where, 0))){
            $where[] = ['status', '>=', 0];//默认获取有效的记录
        }
        //若关联条件存在
        foreach ($whereAssoc as $key => $value){
            self::hasWhere($key, $value);
        }
        return self::where($where)->count();
    }

    /**
     * 获取某个记录的信息
     * @param $id
     * @param array $where
     * @param array $whereAssoc
     * @return array|null|\PDOStatement|string|Model
     */
    public function getDetailById($id, $where=[], $whereAssoc=[]){
        $where[] = ['id', '=', $id];
        //若不指定status
        if (!in_array('status', array_column($where, 0))){
            $where[] = ['status', '>=', 0];//默认获取有效的记录
        }
        $object = $this->where($where);
        //若关联条件存在
        foreach ($whereAssoc as $key => $value) {
            $object = $object->hasWhere($key, $value);
        }
        return $object->with('label')->find();
    }

}